﻿package com.saint.utils{
	
	public class NumberUtils{
		
		public function NumberUtils(){
		}
		
		/**
		 * takes decimal number and returns formatted hexidecimal equivalent
		 * 
		 * @param	dec
		 * @return
		 */
		public static function decimalToHex(dec:Number):String{
			var hex:String = dec.toString(16);
			while(hex.length < 6){
				hex = "0"+hex;
			}
			return hex;
		}
		
		/**
		 * takes a value within a given range and converts it to a number between 0 and 1
		 * 
		 * @param	value
		 * @param	min
		 * @param	max
		 * @return
		 */
		public static function normalize(value:Number, min:Number, max:Number):Number{
			return (value - min) / (max - min);
		}
		
		/**
		 * takes array of values, and normalise them all
		 * 
		 * @param	dataset
		 * @param	min1
		 * @param	max1
		 * @param	min2
		 * @param	max2
		 * @return
		 */ 
		public static function mapArray(dataset:Array, min1:Number, max1:Number, min2:Number, max2:Number):Array{
			var mappedData:Array = [];
			for(var i:int=0; i<dataset.length; i++){
				mappedData.push(map(dataset[i], min1, max1, min2, max2));
			}
			return mappedData;
		}
		
		/**
		 * linear interpolation.
		 * takes a normalized value and a range and returns the actual value for the interpolated value in that range
		 * 
		 * @param	normValue
		 * @param	min
		 * @param	max
		 * @return
		 */
		public static function interpolate(normValue:Number, min:Number, max:Number):Number{
			return min + (max - min) * normValue;
		}
		
		/**
		 * takes a value in a given range (min1, max1) and finds the corresonding value in the next range(min2, max2)
		 * @param	val
		 * @param	min1
		 * @param	max1
		 * @param	min2
		 * @param	max2
		 * @return
		 */
		public static function map(val:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number{
			return interpolate( normalize(val, min1, max1), min2, max2);
		}
		
		/**
		 * returns correct ratio to fit content in a container using maximum area
		 * 
		 * @param	w
		 * @param	h
		 * @param	maxW
		 * @param	maxH
		 * @return
		 */
		public static function findPreferredRatio(w:Number, h:Number, maxW:Number, maxH:Number ):Number{
			var dw:Number = maxW/w;
			var dh:Number = maxH/h;
			return dw < dh ? dw : dh;
		}
		
	}
	
}